package com.atguigu.springcloud.alibaba.service.Impl;

import com.atguigu.springcloud.alibaba.dao.AccountDao;
import com.atguigu.springcloud.alibaba.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * @Author Kevin
 * @Date 2021-04-19 16:18:37
 */
@Service
@Slf4j
public class AccountServiceImpl implements AccountService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Resource
    private AccountDao accountDao;

    private final Integer RANDOM_NUM = 2;

    @Override
    public void decrease(Long userId, BigDecimal money) {
        LOGGER.info("------->account-service中扣减账户余额开始");
        //随机生成100以内的整数，如果能被二整除就模拟超时异常，全局事务回滚
        //暂停几秒钟线程
        int max = 100, min = 1;
        int random = (int) (Math.random() * (max - min) + min);
        LOGGER.info("随机数=" + random);
        if (random % RANDOM_NUM == 0) {
            LOGGER.error("已经进入休眠");
            try {
                TimeUnit.SECONDS.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        accountDao.decrease(userId, money);
        LOGGER.info("------->account-service中扣减账户余额结束");
    }
}
